#include "StdAfx.h"
#include "WinBoardInputThread.h"

#include <Windows.h>

#include <string>

using namespace Rorn::Chess;

DWORD WinBoardInputThreadProc(LPVOID lpdwThreadParam );

WinBoardInputThread::WinBoardInputThread(WinBoardInputQueue& inputQueue)
	: inputQueue_(inputQueue)
{
	LPVOID parameter = static_cast<LPVOID>(&inputQueue_);
	commandListenerThreadHandle_ = ::CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)&WinBoardInputThreadProc, parameter, 0, &commandListenerThreadId_);
}

WinBoardInputThread::~WinBoardInputThread(void)
{
	::CloseHandle(commandListenerThreadHandle_);
}

DWORD WinBoardInputThreadProc(LPVOID parameter )
{
	WinBoardInputQueue* inputQueue = static_cast<WinBoardInputQueue*>(parameter);

	std::string commandInProgress;
	while(true)
	{
		char nextChar = static_cast<char>(getchar());

		if(nextChar == '\n')
		{
			inputQueue->AddMessage(commandInProgress);
			commandInProgress.clear();
		}
		else
		{
			commandInProgress += nextChar;
		}
	}
}